<template>
  <div class="app-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <el-page-header @back="goBack" content="追溯码详情">
        <template slot="title">
          <i class="el-icon-arrow-left"></i>
          <span>返回</span>
        </template>
      </el-page-header>
    </div>

    <!-- 追溯码信息卡片 -->
    <div class="content-section">
      <el-card class="trace-card" shadow="hover">
        <div slot="header" class="card-header">
          <div class="header-title">
            <i class="el-icon-connection"></i>
            <span>追溯码信息</span>
          </div>
          <div class="header-stats">
            <el-tag type="info" size="small">
              查询码: {{ queryBarCode }}
            </el-tag>
            <el-tag type="warning" size="small">
              共 {{ traceInfoList.length }} 条记录
            </el-tag>
            <el-button type="success" icon="el-icon-download" size="mini" @click="handleExportTrace">
              导出追溯码
            </el-button>
          </div>
        </div>

        <!-- 树状结构显示 -->
        <el-tree
          v-if="treeTraceInfo.length > 0"
          :data="treeTraceInfo"
          :props="treeProps"
          node-key="curCode"
          :default-expand-all="true"
          class="trace-tree"
        >
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span class="node-label">
              <el-tag :type="getCodeLevelTagType(data.codeLevel)" size="mini">
                {{ getCodeLevelText(data.codeLevel) }}
              </el-tag>
              <span class="code-text">{{ data.curCode }}</span>
            </span>
            <span class="node-info">
              <span class="scan-time">{{ formatDateTime(data.scanTime) }}</span>
              <el-tag v-if="data.codeState" :type="getCodeStateTagType(data.codeState)" size="mini">
                {{ getCodeStateText(data.codeState) }}
              </el-tag>
            </span>
          </span>
        </el-tree>

        <!-- 如果没有树状数据，显示原始表格 -->
        <el-table
          v-else
          :data="traceInfoList"
          class="trace-table"
          :header-cell-style="{
            fontWeight: '600',
            fontSize: '13px'
          }"
          :row-style="{ height: '50px' }"
          stripe
        >
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column label="当前码" align="center" prop="curCode" min-width="200" show-overflow-tooltip />
          <el-table-column label="码级别" align="center" prop="codeLevel" width="80">
            <template slot-scope="scope">
              <el-tag :type="getCodeLevelTagType(scope.row.codeLevel)">
                {{ getCodeLevelText(scope.row.codeLevel) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="父级码" align="center" prop="parentCode" min-width="200" show-overflow-tooltip />
          <el-table-column label="扫描时间" align="center" prop="scanTime" width="180">
            <template slot-scope="scope">
              {{ formatDateTime(scope.row.scanTime) }}
            </template>
          </el-table-column>
          <el-table-column label="码状态" align="center" prop="codeState" width="80">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.codeState" :type="getCodeStateTagType(scope.row.codeState)">
                {{ getCodeStateText(scope.row.codeState) }}
              </el-tag>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" prop="remark" min-width="120" show-overflow-tooltip />
        </el-table>

        <!-- 空状态 -->
        <div v-if="traceInfoList.length === 0" class="empty-state">
          <el-empty description="未找到相关追溯码信息" />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getBarRelationList } from "@/api/wareHouse/barRelation";

export default {
  name: 'BarRelationTraceDetail',
  data() {
    return {
      // 查询的追溯码
      queryBarCode: '',
      // 码级别
      codeLevel: '',
      // 追溯码信息列表
      traceInfoList: [],
      // 树状组件配置
      treeProps: {
        children: 'children',
        label: 'curCode'
      }
    };
  },
  computed: {
    // 树状结构的追溯码信息
    treeTraceInfo() {
      if (!this.traceInfoList || this.traceInfoList.length === 0) {
        return [];
      }

      // 构建树状结构
      return this.buildTraceTree(this.traceInfoList);
    }
  },
  created() {
    this.queryBarCode = this.$route.query.barCode;
    this.codeLevel = this.$route.query.codeLevel;
    console.log('接收到的追溯码:', this.queryBarCode, '级别:', this.codeLevel);

    if (this.queryBarCode) {
      this.getTraceInfo();
    } else {
      this.$modal.msgError("追溯码不能为空");
    }
  },
  methods: {
    /** 获取追溯码信息 */
    getTraceInfo() {
      if (!this.queryBarCode) {
        this.$modal.msgWarning("追溯码不能为空");
        return;
      }

      console.log('查询追溯码:', this.queryBarCode);
      // 显示所有相关的追溯码信息（不使用层级查询）
      getBarRelationList({ barCode: this.queryBarCode, noPaging: true }).then(response => {
        console.log('获取追溯码信息成功:', response);
        this.traceInfoList = response.rows || [];
      }).catch(error => {
        console.error('获取追溯码信息失败:', error);
        this.$modal.msgError("获取追溯码信息失败");
      });
    },

    /** 返回上一页 */
    goBack() {
      this.$router.go(-1);
    },

    /** 导出追溯码信息 */
    handleExportTrace() {
      if (this.traceInfoList.length === 0) {
        this.$modal.msgWarning("没有可导出的追溯码数据");
        return;
      }

      this.$modal.confirm('是否确认导出追溯码信息？').then(() => {
        this.download('/wareHouse/list/barRelation/export', {
          barCode: this.queryBarCode
        }, `追溯码信息_${this.queryBarCode.substring(0, 8)}_${new Date().getTime()}.xlsx`);
      });
    },

    /** 构建树状结构 */
    buildTraceTree(traceList) {
      if (!traceList || traceList.length === 0) {
        return [];
      }

      // 按码级别分组
      const levelMap = {};
      traceList.forEach(item => {
        const level = item.codeLevel || '1';
        if (!levelMap[level]) {
          levelMap[level] = [];
        }
        levelMap[level].push(item);
      });

      // 构建层级关系
      const result = [];

      // 先添加3级码作为根节点
      if (levelMap['3']) {
        levelMap['3'].forEach(level3 => {
          const node = { ...level3, children: [] };

          // 查找对应的2级码
          if (levelMap['2']) {
            levelMap['2'].forEach(level2 => {
              if (level2.parentCode === level3.curCode) {
                const child2 = { ...level2, children: [] };

                // 查找对应的1级码
                if (levelMap['1']) {
                  levelMap['1'].forEach(level1 => {
                    if (level1.parentCode === level2.curCode) {
                      child2.children.push({ ...level1 });
                    }
                  });
                }

                node.children.push(child2);
              }
            });
          }

          result.push(node);
        });
      }

      // 如果没有3级码，直接显示2级码
      else if (levelMap['2']) {
        levelMap['2'].forEach(level2 => {
          const node = { ...level2, children: [] };

          // 查找对应的1级码
          if (levelMap['1']) {
            levelMap['1'].forEach(level1 => {
              if (level1.parentCode === level2.curCode) {
                node.children.push({ ...level1 });
              }
            });
          }

          result.push(node);
        });
      }

      // 如果只有1级码，直接显示
      else if (levelMap['1']) {
        result.push(...levelMap['1']);
      }

      return result;
    },

    /** 格式化日期时间 */
    formatDateTime(dateTime) {
      if (!dateTime) return '-';

      // 处理SQL Server的datetime格式：2025-03-19 15:02:21.9470000
      const date = new Date(dateTime);
      if (isNaN(date.getTime())) return dateTime;

      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    /** 获取码级别标签类型 */
    getCodeLevelTagType(codeLevel) {
      switch (codeLevel) {
        case '3': return 'danger';
        case '2': return 'warning';
        case '1': return 'success';
        default: return 'info';
      }
    },

    /** 获取码级别文本 */
    getCodeLevelText(codeLevel) {
      switch (codeLevel) {
        case '3': return '3级码';
        case '2': return '2级码';
        case '1': return '1级码';
        default: return '未知';
      }
    },

    /** 获取码状态标签类型 */
    getCodeStateTagType(codeState) {
      switch (codeState) {
        case '1': return 'success';
        case '0': return 'danger';
        default: return 'info';
      }
    },

    /** 获取码状态文本 */
    getCodeStateText(codeState) {
      switch (codeState) {
        case '1': return '正常';
        case '0': return '异常';
        default: return '未知';
      }
    }
  }
};
</script>

<style scoped>
.page-header {
  margin-bottom: 20px;
}

.content-section {
  margin-bottom: 20px;
}

.trace-card {
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.header-title i {
  margin-right: 8px;
  color: #409EFF;
}

.header-stats {
  display: flex;
  align-items: center;
  gap: 10px;
}

.trace-tree {
  margin-top: 10px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.node-label {
  display: flex;
  align-items: center;
  gap: 8px;
}

.code-text {
  font-family: 'Courier New', monospace;
  font-weight: 500;
}

.node-info {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
  color: #909399;
}

.scan-time {
  font-size: 12px;
}

.trace-table {
  margin-top: 10px;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}

/* 表格样式优化 */
::v-deep .el-table .el-table__row:hover {
  background-color: #f8f9ff;
}

::v-deep .el-table .el-table__header-wrapper th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

/* 树状组件样式优化 */
::v-deep .el-tree-node__content {
  height: 40px;
  border-bottom: 1px solid #f0f0f0;
}

::v-deep .el-tree-node__content:hover {
  background-color: #f8f9ff;
}
</style>
